//app.js
var innerAudioContext;
App({
  onLaunch: function () {
    //设置服务器地址
    wx.setStorage({
      key: 'request_url',
      data: 'https://mjj.arearth.com'
    });
    // 展示本地存储能力
    var logs = wx.getStorageSync('logs') || []
    logs.unshift(Date.now())
    wx.setStorageSync('logs', logs)
    //加载音乐
    var bgmExist = wx.getStorageSync("bgm");
    if (!bgmExist) {
      console.log("第一次加载游戏");
      for (var i = 0; i < 5; i++) {
        this.downLoadAudio(i);
      }
    }
    // 登录
    // wx.login({
    //   success: res => {
    //     // 发送 res.code 到后台换取 openId, sessionKey, unionId
    //   }
    // })
    wx.login({
      success: function (res) {
        console.log(res)
        if (res.code) {
          console.log('获取用户登录态成功！');
          var request_url = wx.getStorageSync('request_url')
          var nickName = wx.getStorageSync('nickName')
          console.log(nickName)
          wx.request({      //初始化用户信息
            url: request_url+"/MianJuJiang/user/init/",
            method:"post",
            data: 'code=' + res.code,
            // +'&nick=' + nickName,
            header: {
              'content-type': 'application/x-www-form-urlencoded',
              'Accept': 'application/json'
            },
            success: function (response) {
              //code = -2: 不是用POST方法请求的
              // -1 openId为空
              // 0 用户第一次使用本程序，保存用户成功
              // 1 用户不是第一次使用
              console.log(response.data)
              //保存openId
              var openid = response.data.openId
              wx.setStorage({
                key: 'openid',
                data: openid,
              })
              //保存difficulty
              var difficulty = response.data.difficulty
              wx.setStorage({
                key: 'difficulty',
                data: difficulty,
              })
              var code = response.data["code"]
              wx.setStorage({
                key: 'code',
                data: code,
              })
              console.log("code: " + code);
            }
          })
        } else {
          console.log('用户初始化失败...' + res.errMsg);
        }
      }
    })

    // 获取用户信息
    wx.getSetting({
      success: res => {
        if (res.authSetting['scope.userInfo']) {
          // 已经授权，可以直接调用 getUserInfo 获取头像昵称，不会弹框
          wx.getUserInfo({
            success: res => {
              console.log(res)
              console.log(res.userInfo)
              console.log(res.userInfo.nickName)
              // 可以将 res 发送给后台解码出 unionId
              this.globalData.userInfo = res.userInfo
              var nickName = res.userInfo.nickName
              console.log(nickName)
              wx.setStorage({
                key: 'nickName',
                data: nickName,
              })
              // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
              // 所以此处加入 callback 以防止这种情况
              if (this.userInfoReadyCallback) {
                this.userInfoReadyCallback(res)
              }
            }
          })
        }
      }
    })
  },

  downLoadAudio: function (i) {
    var that = this;
    var urlList = ["/bgm.mp3", "/button1.mp3", "/button2.mp3", "/countdown.mp3", "/matchsuccess.mp3"]
    var urlStorageKey = ["bgm", "button1", "button2", "countdown", "matchsuccess"]
    //下载音频文件
    var url = "https://mjj.arearth.com/sound" + urlList[i];
    // console.log(url);
    var urlKey = urlStorageKey[i];
    wx.downloadFile({
      url: url,
      success: function (res) {
        var tempFilePath = res.tempFilePath;
        wx.setStorageSync(urlKey, res.tempFilePath);
        console.log(wx.getStorageSync(urlKey) + "    " + i);
        if (i == 0) { that.startAudio() }
      },
      fail: function () {
        console.log("音频下载失败")
      }
    })
  },
  startAudio: function () {
    innerAudioContext = wx.createInnerAudioContext()
    innerAudioContext.autoplay = true;
    innerAudioContext.src = wx.getStorageSync("bgm");
    innerAudioContext.loop = true;
    console.log("开始播放")

  },
  stopbgAudio: function () {
    innerAudioContext.stop();
  },
  onShow:function(){
    this.startAudio();
  },

  onHide:function(){
    this.stopbgAudio();
  },

  globalData: {
    userInfo: null
  }
})